<template>
	<u-popup :show="show" mode="bottom" closeOnClickOverlay :border-radius="20" @close="handleClose"
		:safe-area-inset-bottom="false">
		<view class="product-detail-popup">
			<!-- 关闭按钮 -->
			<view class="close-btn" @click="handleClose">
				<u-icon name="close" size="20" color="#000000"></u-icon>
			</view>

			<!-- 商品信息 -->
			<view class="product-info">
				<view class="product-image">
					<image :src="product.image" mode="aspectFill" class="product-img"></image>
				</view>
				<view class="product-details">
					<text class="product-name">{{ product.name }}</text>
					<text class="stock-info">库存数量：{{ product.stock || 65 }}</text>
					<text class="selected-info">已选：{{ selectedSpec }}</text>
				</view>
			</view>

			<!-- 规格选择 -->
			<view class="spec-section" v-for="(spec, specIndex) in computedSpecOptions" :key="spec.id">
				<text class="section-title">{{ spec.content || spec.name }}<text v-if="spec.isMust"
						class="required">*</text></text>
				<view class="spec-options">
					<view class="spec-option" v-for="(value, valueIndex) in getSpecValues(spec)"
						:key="value.id || valueIndex" :class="{ active: selectedAttributes[spec.id] === value.content }"
						@click="selectAttribute(spec.id, value.content)">
						<text class="spec-text">{{ value.content }}</text>
						<!-- <text v-if="value.price" class="spec-price">+¥{{ value.price }}</text> -->
					</view>
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="action-bar">
				<view class="price-section">
					<!-- 会员价格显示 -->
					<view v-if="Userinfo.vip && product.vipPrice" class="vip-price-container">
						<view class="vip-price">
							<text class="price-symbol vip-symbol">¥</text>
							<text class="price-amount vip-amount">{{ selectedSpecVipPrice }}</text>
						</view>
						<view class="original-price">
							<text class="price-symbol">¥</text>
							<text class="price-amount original-amount">{{ selectedSpecPrice }}</text>
						</view>
					</view>
					<!-- 非会员价格显示 -->
					<view v-else class="normal-price flex-align-center">
						<view class="flex-align-center">
							<text class="price-symbol">¥</text>
							<text class="price-amount">{{ selectedSpecPrice }}</text>
						</view>
						<!-- 非会员用户显示会员价标签 -->
						<view v-if="!Userinfo.vip && product.vipPrice" class="member-tag">
							会员价 ¥{{ selectedSpecVipPrice }}
						</view>
					</view>
				</view>
				<view class="add-cart-btn" @click="handleAddToCart">
					<text class="add-cart-text">加入购物车</text>
				</view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import {
		addToDiningCart,
		getDiningCartList
	} from '@/api/restaurant.js'
	import {
		addToCart
	} from '@/api/mall.js'

	export default {
		name: 'ProductDetailPopup',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			product: {
				type: Object,
				default: () => ({})
			},
			productType: {
				type: String,
				default: 'food', // 'food' 餐饮商品, 'mall' 商城商品
				validator: value => ['food', 'mall'].includes(value)
			},
			specOptions: {
				type: Array,
				default: () => [{
						name: '小份500g'
					},
					{
						name: '大份1000g'
					}
				]
			},
			flavorOptions: {
				type: Array,
				default: () => [{
						name: '微辣'
					},
					{
						name: '中辣'
					},
					{
						name: '爆辣'
					}
				]
			}
		},
		data() {
			return {
				selectedSpecIndex: 0,
				selectedFlavorIndex: 0,
				selectedAttributes: {} // 存储选中的属性
			}
		},
		watch: {
			// 监听规格选项变化，自动选择第一个选项
			computedSpecOptions: {
				handler(newSpecOptions) {
					if (newSpecOptions && newSpecOptions.length > 0) {
						this.initializeDefaultSelection(newSpecOptions);
					}
				},
				immediate: true
			}
		},
		computed: {
			// 从商品数据中提取规格选项
			computedSpecOptions() {
				console.log('ProductDetailPopup: 计算规格选项');
				console.log('specOptions:', this.specOptions);
				console.log('product:', this.product);

				// 优先使用从父组件传递的规格数据
				if (this.specOptions && this.specOptions.length > 0) {
					console.log('使用父组件传递的规格数据:', this.specOptions);
					return this.specOptions;
				}

				// 如果没有传递规格数据，尝试从商品数据中提取
				if (this.product && this.product.attributeKeys && this.product.attributeKeys.length > 0) {
					console.log('从商品数据中提取规格:', this.product.attributeKeys);
					return this.product.attributeKeys.map(key => {
						const values = this.product.attributeValues?.filter(val => val.keyId === key.id) || []
						return {
							id: key.id,
							content: key.content, // 使用content字段
							name: key.content, // 兼容name字段
							isMust: key.isMust === '1',
							attributeValues: values // 使用attributeValues字段
						}
					})
				}

				// 默认返回空数组
				console.log('没有找到规格数据，返回空数组');
				return [];
			},
			// 选中的规格 - 动态获取所有选中的规格
			selectedSpec() {
				console.log('ProductDetailPopup: 计算selectedSpec');
				console.log('computedSpecOptions:', this.computedSpecOptions);
				console.log('selectedAttributes:', this.selectedAttributes);

				// 动态获取所有选中的规格
				const selectedSpecs = [];
				
				this.computedSpecOptions.forEach(spec => {
					if (spec && spec.id) {
						const selectedValue = this.selectedAttributes[spec.id];
						if (selectedValue) {
							selectedSpecs.push(selectedValue);
						} else {
							// 如果没有选中，使用第一个选项
							const values = this.getSpecValues(spec);
							if (values.length > 0) {
								selectedSpecs.push(values[0]?.content || spec.content || spec.name);
							}
						}
					}
				});

				const result = selectedSpecs.join('/');
				console.log('selectedSpec result:', result);
				return result || '默认规格';
			},
			// 选中的口味 - 兼容旧版本，现在返回空字符串避免显示undefined
			selectedFlavor() {
				console.log('ProductDetailPopup: 计算selectedFlavor');
				console.log('computedSpecOptions.length:', this.computedSpecOptions.length);

				// 如果只有一个规格，返回空字符串避免显示undefined
				if (this.computedSpecOptions.length <= 1) {
					return '';
				}

				// 如果有多个规格，返回除第一个之外的所有规格
				const otherSpecs = [];
				for (let i = 1; i < this.computedSpecOptions.length; i++) {
					const spec = this.computedSpecOptions[i];
					if (spec && spec.id) {
						const selectedValue = this.selectedAttributes[spec.id];
						if (selectedValue) {
							otherSpecs.push(selectedValue);
						} else {
							const values = this.getSpecValues(spec);
							if (values.length > 0) {
								otherSpecs.push(values[0]?.content || spec.content || spec.name);
							}
						}
					}
				}

				const result = otherSpecs.join('/');
				console.log('selectedFlavor result:', result);
				return result;
			},

			// 计算选中规格的价格
			selectedSpecPrice() {
				console.log('ProductDetailPopup: 计算selectedSpecPrice');
				console.log('selectedAttributes:', this.selectedAttributes);
				console.log('product.price:', this.product.price);

				// 如果有选中的规格，显示选中规格的价格
				if (Object.keys(this.selectedAttributes).length > 0) {
					// 获取第一个选中的规格价格（假设只有一个规格）
					const firstSelectedValue = Object.values(this.selectedAttributes)[0];
					console.log('firstSelectedValue:', firstSelectedValue);

					// 在所有规格中查找对应的价格
					for (let spec of this.computedSpecOptions) {
						if (spec) {
							const values = this.getSpecValues(spec);
							const matchedValue = values.find(val => val && val.content === firstSelectedValue);
							if (matchedValue && matchedValue.price) {
								const price = parseFloat(matchedValue.price).toFixed(2);
								console.log('找到匹配价格:', price);
								return price;
							}
						}
					}
				}

				// 如果没有选中规格，显示商品基础价格
				const fallbackPrice = (this.product && parseFloat(this.product.price)) || 0;
				console.log('使用基础价格:', fallbackPrice);
				return fallbackPrice.toFixed(2);
			},
			
			// 计算选中规格的VIP价格
			selectedSpecVipPrice() {
				console.log('ProductDetailPopup: 计算selectedSpecVipPrice');
				console.log('product.vipPrice:', this.product.vipPrice);

				// 如果有选中的规格，显示选中规格的VIP价格
				if (Object.keys(this.selectedAttributes).length > 0) {
					// 获取第一个选中的规格价格（假设只有一个规格）
					const firstSelectedValue = Object.values(this.selectedAttributes)[0];
					console.log('firstSelectedValue:', firstSelectedValue);

					// 在所有规格中查找对应的VIP价格
					for (let spec of this.computedSpecOptions) {
						if (spec) {
							const values = this.getSpecValues(spec);
							const matchedValue = values.find(val => val && val.content === firstSelectedValue);
							if (matchedValue && matchedValue.vipPrice) {
								const vipPrice = parseFloat(matchedValue.vipPrice).toFixed(2);
								console.log('找到匹配VIP价格:', vipPrice);
								return vipPrice;
							}
						}
					}
				}

				// 如果没有选中规格，显示商品基础VIP价格
				const fallbackVipPrice = (this.product && parseFloat(this.product.vipPrice)) || 0;
				console.log('使用基础VIP价格:', fallbackVipPrice);
				return fallbackVipPrice.toFixed(2);
			},
			Userinfo() {
				this.userinfo = this.$store.state.userinfo;
				return this.$store.state.userinfo;
			}
		},
		methods: {
			// 安全获取规格值
			getSpecValues(spec) {
				if (!spec) {
					console.warn('getSpecValues: spec is undefined');
					return [];
				}

				const values = spec.attributeValues || spec.values || [];
				if (!Array.isArray(values)) {
					console.warn('getSpecValues: values is not an array', values);
					return [];
				}

				return values;
			},

			// 初始化默认选择
			initializeDefaultSelection(specOptions) {
				console.log('ProductDetailPopup: 初始化默认选择', specOptions);

				// 清空之前的选择
				this.selectedAttributes = {};

				// 为每个规格选择第一个选项
				specOptions.forEach(spec => {
					if (spec && spec.id) {
						const values = this.getSpecValues(spec);
						if (values.length > 0) {
							const firstValue = values[0];
							if (firstValue && firstValue.content) {
								this.$set(this.selectedAttributes, spec.id, firstValue.content);
								console.log(
									`ProductDetailPopup: 自动选择规格 ${spec.content || spec.name} 的第一个选项: ${firstValue.content}`
									);
							}
						}
					}
				});

				console.log('ProductDetailPopup: 默认选择完成:', this.selectedAttributes);
			},

			// 选择属性
			selectAttribute(keyId, value) {
				this.$set(this.selectedAttributes, keyId, value);
				console.log('选择规格:', keyId, value);
				console.log('当前选中的属性:', this.selectedAttributes);
				console.log('选中规格的价格:', this.selectedSpecPrice);
			},

			// 选择规格（兼容旧版本）
			selectSpec(index) {
				this.selectedSpecIndex = index;
			},

			// 选择口味（兼容旧版本）
			selectFlavor(index) {
				this.selectedFlavorIndex = index;
			},

			// 关闭弹出框
			handleClose() {
				this.$emit('close');
			},

			// 加入购物车
			handleAddToCart() {
				console.log('ProductDetailPopup: 准备加入购物车');
				console.log('选中的属性:', this.selectedAttributes);
				console.log('生成的attributeIds:', this.getAttributeIds());

				const userId = this.$store.state.userid || 'user_12345'
				const cartItem = {
					...this.product,
					spec: this.selectedSpec,
					flavor: this.selectedFlavor,
					quantity: 1,
					checked: true
				};

				// 根据商品类型调用不同的API
				if (this.productType === 'food') {
					// 餐饮商品
					addToDiningCart({
						productId: this.product.id,
						userId: userId,
						count: 1,
						attributeIds: this.getAttributeIds()
					}).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '已加入购物车',
								icon: 'success'
							})

							// 自动刷新购物车数据
							this.refreshCartData();

							// 触发事件通知父组件
							this.$emit('add-to-cart', cartItem);
							this.handleClose();
						} else {
							uni.showToast({
								title: res.message || '加入购物车失败',
								icon: 'none'
							})
						}
					}).catch(err => {
						console.error('加入购物车失败:', err)
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					})
				} else {
					// 商城商品
					addToCart({
						productId: this.product.id,
						userId: userId,
						count: 1,
						productPrice: this.product.price,
						productName: this.product.name,
						productImg: this.product.image,
						specId: this.getAttributeIds()
					}).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '已加入购物车',
								icon: 'success'
							})
							this.$emit('add-to-cart', cartItem);
							this.handleClose();
						} else {
							uni.showToast({
								title: res.message || '加入购物车失败',
								icon: 'none'
							})
						}
					}).catch(err => {
						console.error('加入购物车失败:', err)
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					})
				}
			},

			// 刷新购物车数据
			refreshCartData() {
				if (this.productType === 'food') {
					const userId = this.$store.state.userid || 'user_12345'
					getDiningCartList({
						userId: userId
					}).then(res => {
						if (res.code == 200) {
							console.log('ProductDetailPopup: 购物车数据已刷新', res.data);
							// 触发事件通知父组件更新购物车数据
							this.$emit('cart-updated', res.data || []);
						}
					}).catch(err => {
						console.error('ProductDetailPopup: 刷新购物车数据失败:', err);
					});
				}
			},

			// 获取属性ID字符串
			getAttributeIds() {
				// 根据选中的属性生成属性ID字符串
				const attributeIds = [];

				console.log('当前选中的属性:', this.selectedAttributes);
				console.log('规格选项:', this.computedSpecOptions);

				Object.keys(this.selectedAttributes).forEach(keyId => {
					const selectedValue = this.selectedAttributes[keyId];
					console.log('查找规格ID:', keyId, '选中的值:', selectedValue);

					// 在规格选项中查找对应的属性值ID
					for (let spec of this.computedSpecOptions) {
						if (spec && spec.id === keyId) {
							const values = this.getSpecValues(spec);
							const matchedValue = values.find(val => val && val.content === selectedValue);
							if (matchedValue && matchedValue.id) {
								console.log('找到匹配的属性值ID:', matchedValue.id);
								attributeIds.push(matchedValue.id);
							}
						}
					}
				});

				const result = attributeIds.join(',');
				console.log('生成的attributeIds:', result);
				return result;
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 商品详情弹出框样式
	.product-detail-popup {
		padding: 40rpx;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		max-height: 60vh;
		min-height: 50vh;

		.close-btn {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			width: 40rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.product-info {
			display: flex;
			margin-bottom: 40rpx;

			.product-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				overflow: hidden;
				margin-right: 20rpx;

				.product-img {
					width: 100%;
					height: 100%;
				}
			}

			.product-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.product-name {
					font-size: 32rpx;
					color: #333333;
					font-weight: 500;
					margin-bottom: 10rpx;
				}

				.stock-info {
					font-size: 24rpx;
					color: #666666;
					margin-bottom: 10rpx;
				}

				.selected-info {
					font-size: 24rpx;
					color: #DB0000;
				}
			}
		}

		.spec-section,
		.flavor-section {
			margin-bottom: 40rpx;

			.section-title {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
				margin-bottom: 20rpx;

				.required {
					color: #DB0000;
					margin-left: 4rpx;
				}
			}

			.spec-options,
			.flavor-options {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.spec-option,
				.flavor-option {
					padding: 16rpx 32rpx;
					border: 2rpx solid #EEEEEE;
					border-radius: 8rpx;
					background-color: #fff;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-right: 20rpx;

					&.active {
						border-color: #DB0000;
						background-color: #FFF5F5;

						.spec-text,
						.flavor-text {
							color: #DB0000;
						}
					}

					.spec-text,
					.flavor-text {
						font-size: 26rpx;
						color: #333333;
					}

					.spec-price {
						font-size: 24rpx;
						color: #DB0000;
						margin-left: 8rpx;
					}
				}
			}
		}

		.action-bar {
			display: flex;
			align-items: center;
			justify-content: space-between;
			// padding-top: 20rpx;
			border-top: 2rpx solid #F5F5F5;
			position: fixed;
			bottom: 0%;
			left: 0%;
			width: 100%;
			padding: 20rpx;

			.price-section {
				.vip-price-container {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					
					.vip-price {
						display: flex;
						align-items: baseline;
						margin-bottom: 4rpx;
						
						.vip-symbol {
							font-size: 28rpx;
							color: #FF6B35;
							line-height: 1em;
						}
						
						.vip-amount {
							font-size: 40rpx;
							color: #FF6B35;
							line-height: 1em;
							font-weight: 600;
						}
					}
					
					.original-price {
						display: flex;
						align-items: baseline;
						
						.price-symbol {
							font-size: 24rpx;
							color: #999999;
							line-height: 1em;
						}
						
						.original-amount {
							font-size: 28rpx;
							color: #999999;
							line-height: 1em;
							font-weight: 400;
							text-decoration: line-through;
						}
					}
				}
				
				.normal-price {
					.price-symbol {
						font-size: 28rpx;
						color: #DB0000;
						line-height: 1em;
					}
					
					.price-amount {
						font-size: 40rpx;
						color: #DB0000;
						line-height: 1em;
						font-weight: 600;
					}
					
					.member-tag {
						background: linear-gradient(0deg, #FED590 0%, #FFE8BA 100%);
						border-radius: 8rpx;
						padding: 4rpx 12rpx;
						font-size: 22rpx;
						color: #9C5F1F;
						white-space: nowrap;
						margin-top: -20rpx;
						margin-left: 10rpx;
					}
				}
			}

			.add-cart-btn {
				background-color: #DB0000;
				padding: 20rpx 40rpx;
				border-radius: 8rpx;

				.add-cart-text {
					font-size: 28rpx;
					color: #fff;
					font-weight: 500;
				}
			}
		}
	}
</style>